package com.longge;

public class Exist {

    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                Boolean flag = dfs(board, i, j, visited, word, 0);
                if (flag) return true;
            }
        }
        return false;
    }

    private Boolean dfs(char[][] board, int m, int n, boolean[][] visited, String word, int i) {
        if (board[m][n] != word.charAt(i)) {
            return false;
        }
        if (i == word.length() - 1) {
            return true;
        }
        int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        visited[m][n] = true;
        for (int[] direction : directions) {
            int newM = m + direction[0];
            int newN = n + direction[1];
            if (newM >= 0 && newM < board.length && newN >= 0 && newN < board[0].length) {
                if (!visited[newM][newN]) {
                    Boolean flag = dfs(board, newM, newN, visited, word, i + 1);
                    if (flag) {
                        return true;
                    }
                }
            }
        }
        visited[m][n] = false;
        return false;

    }


}


